package com.library;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.*;

public class LibrarySystem extends JFrame {
    private static final long serialVersionUID = 1L;
    
    // MySQL数据库连接配置
    private static final String DB_URL = "jdbc:mysql://localhost:3306/library_db";
    private static final String DB_USER = "root";  // 请修改为你的MySQL用户名
    private static final String DB_PASSWORD = "123456";  // 请修改为你的MySQL密码
    
    // 界面组件
    private JTable bookTable;
    private DefaultTableModel tableModel;
    private JTextField idField, titleField, authorField, yearField;
    
    public LibrarySystem() {
        // 设置窗口
        setTitle("图书管理系统");
        setSize(800, 600);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);
        
        // 创建数据库和表
        createDatabase();
        createTable();
        
        // 创建表格
        String[] columns = {"ID", "书名", "作者", "出版年份"};
        tableModel = new DefaultTableModel(columns, 0);
        bookTable = new JTable(tableModel);
        JScrollPane scrollPane = new JScrollPane(bookTable);
        
        // 创建输入面板
        JPanel inputPanel = new JPanel(new GridLayout(4, 2, 10, 10));
        idField = new JTextField();
        titleField = new JTextField();
        authorField = new JTextField();
        yearField = new JTextField();
        
        inputPanel.add(new JLabel("图书ID:"));
        inputPanel.add(idField);
        inputPanel.add(new JLabel("书名:"));
        inputPanel.add(titleField);
        inputPanel.add(new JLabel("作者:"));
        inputPanel.add(authorField);
        inputPanel.add(new JLabel("出版年份:"));
        inputPanel.add(yearField);
        
        // 创建按钮面板
        JPanel buttonPanel = new JPanel();
        JButton addButton = new JButton("添加图书");
        JButton updateButton = new JButton("更新图书");
        JButton deleteButton = new JButton("删除图书");
        JButton refreshButton = new JButton("刷新列表");
        
        addButton.addActionListener(new AddBookListener());
        updateButton.addActionListener(new UpdateBookListener());
        deleteButton.addActionListener(new DeleteBookListener());
        refreshButton.addActionListener(new RefreshListener());
        
        buttonPanel.add(addButton);
        buttonPanel.add(updateButton);
        buttonPanel.add(deleteButton);
        buttonPanel.add(refreshButton);
        
        // 组装界面
        JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
        splitPane.setTopComponent(scrollPane);
        
        JPanel bottomPanel = new JPanel(new BorderLayout());
        bottomPanel.add(inputPanel, BorderLayout.CENTER);
        bottomPanel.add(buttonPanel, BorderLayout.SOUTH);
        
        splitPane.setBottomComponent(bottomPanel);
        splitPane.setDividerLocation(400);
        
        add(splitPane);
        
        // 初始化图书列表
        refreshBookList();
    }
    
    // 创建数据库
    private void createDatabase() {
        String sql = "CREATE DATABASE IF NOT EXISTS library_db";
        
        try (Connection conn = DriverManager.getConnection(
                "jdbc:mysql://localhost:3306", DB_USER, DB_PASSWORD);
             Statement stmt = conn.createStatement()) {
            stmt.execute(sql);
        } catch (SQLException e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(null, 
                    "数据库连接失败，请检查配置: " + e.getMessage(), 
                    "错误", JOptionPane.ERROR_MESSAGE);
            System.exit(1);
        }
    }
    
    // 创建数据表
    private void createTable() {
        String sql = "CREATE TABLE IF NOT EXISTS books ("
                + "id INT PRIMARY KEY AUTO_INCREMENT,"
                + "title VARCHAR(255) NOT NULL,"
                + "author VARCHAR(255) NOT NULL,"
                + "year INT"
                + ")";
        
        try (Connection conn = getConnection();
             Statement stmt = conn.createStatement()) {
            stmt.execute(sql);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    
    // 获取数据库连接
    private Connection getConnection() throws SQLException {
        return DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD);
    }
    
    // 刷新图书列表
    private void refreshBookList() {
        tableModel.setRowCount(0);
        String sql = "SELECT * FROM books";
        
        try (Connection conn = getConnection();
             Statement stmt = conn.createStatement();
             ResultSet rs = stmt.executeQuery(sql)) {
            
            while (rs.next()) {
                int id = rs.getInt("id");
                String title = rs.getString("title");
                String author = rs.getString("author");
                int year = rs.getInt("year");
                
                tableModel.addRow(new Object[]{id, title, author, year});
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    
    // 添加图书监听器
    private class AddBookListener implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent e) {
            String title = titleField.getText().trim();
            String author = authorField.getText().trim();
            String yearStr = yearField.getText().trim();
            
            if (title.isEmpty() || author.isEmpty()) {
                JOptionPane.showMessageDialog(null, "书名和作者不能为空!", "错误", JOptionPane.ERROR_MESSAGE);
                return;
            }
            
            int year = 0;
            if (!yearStr.isEmpty()) {
                try {
                    year = Integer.parseInt(yearStr);
                } catch (NumberFormatException ex) {
                    JOptionPane.showMessageDialog(null, "出版年份必须是数字!", "错误", JOptionPane.ERROR_MESSAGE);
                    return;
                }
            }
            
            String sql = "INSERT INTO books (title, author, year) VALUES (?, ?, ?)";
            
            try (Connection conn = getConnection();
                 PreparedStatement pstmt = conn.prepareStatement(sql)) {
                
                pstmt.setString(1, title);
                pstmt.setString(2, author);
                pstmt.setInt(3, year);
                
                pstmt.executeUpdate();
                JOptionPane.showMessageDialog(null, "图书添加成功!", "成功", JOptionPane.INFORMATION_MESSAGE);
                refreshBookList();
                clearFields();
            } catch (SQLException ex) {
                ex.printStackTrace();
                JOptionPane.showMessageDialog(null, "添加图书失败: " + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
            }
        }
    }
    
    // 更新图书监听器
    private class UpdateBookListener implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent e) {
            String idStr = idField.getText().trim();
            String title = titleField.getText().trim();
            String author = authorField.getText().trim();
            String yearStr = yearField.getText().trim();
            
            if (idStr.isEmpty()) {
                JOptionPane.showMessageDialog(null, "请输入要更新的图书ID!", "错误", JOptionPane.ERROR_MESSAGE);
                return;
            }
            
            if (title.isEmpty() && author.isEmpty() && yearStr.isEmpty()) {
                JOptionPane.showMessageDialog(null, "至少需要更新一个字段!", "错误", JOptionPane.ERROR_MESSAGE);
                return;
            }
            
            int id = 0;
            try {
                id = Integer.parseInt(idStr);
            } catch (NumberFormatException ex) {
                JOptionPane.showMessageDialog(null, "图书ID必须是数字!", "错误", JOptionPane.ERROR_MESSAGE);
                return;
            }
            
            int year = 0;
            if (!yearStr.isEmpty()) {
                try {
                    year = Integer.parseInt(yearStr);
                } catch (NumberFormatException ex) {
                    JOptionPane.showMessageDialog(null, "出版年份必须是数字!", "错误", JOptionPane.ERROR_MESSAGE);
                    return;
                }
            }
            
            StringBuilder sqlBuilder = new StringBuilder("UPDATE books SET ");
            boolean hasUpdate = false;
            
            if (!title.isEmpty()) {
                sqlBuilder.append("title = ?, ");
                hasUpdate = true;
            }
            
            if (!author.isEmpty()) {
                sqlBuilder.append("author = ?, ");
                hasUpdate = true;
            }
            
            if (!yearStr.isEmpty()) {
                sqlBuilder.append("year = ?, ");
                hasUpdate = true;
            }
            
            if (!hasUpdate) return;
            
            // 移除最后一个逗号和空格
            sqlBuilder.delete(sqlBuilder.length() - 2, sqlBuilder.length());
            sqlBuilder.append(" WHERE id = ?");
            
            try (Connection conn = getConnection();
                 PreparedStatement pstmt = conn.prepareStatement(sqlBuilder.toString())) {
                
                int paramIndex = 1;
                if (!title.isEmpty()) pstmt.setString(paramIndex++, title);
                if (!author.isEmpty()) pstmt.setString(paramIndex++, author);
                if (!yearStr.isEmpty()) pstmt.setInt(paramIndex++, year);
                pstmt.setInt(paramIndex, id);
                
                int rowsAffected = pstmt.executeUpdate();
                if (rowsAffected > 0) {
                    JOptionPane.showMessageDialog(null, "图书更新成功!", "成功", JOptionPane.INFORMATION_MESSAGE);
                    refreshBookList();
                    clearFields();
                } else {
                    JOptionPane.showMessageDialog(null, "未找到指定ID的图书!", "错误", JOptionPane.ERROR_MESSAGE);
                }
            } catch (SQLException ex) {
                ex.printStackTrace();
                JOptionPane.showMessageDialog(null, "更新图书失败: " + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
            }
        }
    }
    
    // 删除图书监听器
    private class DeleteBookListener implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent e) {
            String idStr = idField.getText().trim();
            
            if (idStr.isEmpty()) {
                JOptionPane.showMessageDialog(null, "请输入要删除的图书ID!", "错误", JOptionPane.ERROR_MESSAGE);
                return;
            }
            
            int id = 0;
            try {
                id = Integer.parseInt(idStr);
            } catch (NumberFormatException ex) {
                JOptionPane.showMessageDialog(null, "图书ID必须是数字!", "错误", JOptionPane.ERROR_MESSAGE);
                return;
            }
            
            int confirm = JOptionPane.showConfirmDialog(null, 
                    "确定要删除ID为" + id + "的图书吗?", 
                    "确认删除", JOptionPane.YES_NO_OPTION);
            
            if (confirm == JOptionPane.YES_OPTION) {
                String sql = "DELETE FROM books WHERE id = ?";
                
                try (Connection conn = getConnection();
                     PreparedStatement pstmt = conn.prepareStatement(sql)) {
                    
                    pstmt.setInt(1, id);
                    int rowsAffected = pstmt.executeUpdate();
                    
                    if (rowsAffected > 0) {
                        JOptionPane.showMessageDialog(null, "图书删除成功!", "成功", JOptionPane.INFORMATION_MESSAGE);
                        refreshBookList();
                        clearFields();
                    } else {
                        JOptionPane.showMessageDialog(null, "未找到指定ID的图书!", "错误", JOptionPane.ERROR_MESSAGE);
                    }
                } catch (SQLException ex) {
                    ex.printStackTrace();
                    JOptionPane.showMessageDialog(null, "删除图书失败: " + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
                }
            }
        }
    }
    
    // 刷新监听器
    private class RefreshListener implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent e) {
            refreshBookList();
            clearFields();
        }
    }
    
    // 清空输入字段
    private void clearFields() {
        idField.setText("");
        titleField.setText("");
        authorField.setText("");
        yearField.setText("");
    }
    
    public static void main(String[] args) {
        // 确保中文正常显示
        System.setProperty("file.encoding", "UTF-8");
        
        SwingUtilities.invokeLater(() -> {
            LibrarySystem system = new LibrarySystem();
            system.setVisible(true);
        });
    }
}    